# coding:utf-8
# 事件管理

import traceback, datetime, uuid
from sqlalchemy import and_, or_
import glog, gdb
from db_tables import *
from event import *


# { role_id : [event, ..], .. }
data = None


def init ():
    glog.log('event_mgr>init')
    _load_from_db()


# 启动时载入内存
def _load_from_db ():
    global data
    if not data is None: return
    glog.log('event_mgr>_load_from_db')

    data = {}
    dbevents = db_get_all_events()
    for dbevent in dbevents:
        event = Event()
        _dbevent_to_event(dbevent, event)
        if event.role_id not in data: 
            data[event.role_id] = []
        data[event.role_id].append(event)

    print "event_mgr data:", data


# 取得角色事件列表
def _get_events_by_role_id (role_id):
    global data
    if role_id not in data: return []
    return data[role_id]


def _get_events_by_role_id_and_type (role_id, event_type):
    global data
    for e in _get_events_by_role_id(role_id):
        if e.type == event_type:
            return e


# 增加个事件
def add_event (role_id, event_type):
    global data
    events = _get_events_by_role_id(role_id)
    if len(events) >= 1:
        return False, '同时只能做一件事情'

    # 数据库
    id = uuid.uuid1().hex
    if not db_create_event(id, role_id, event_type):
        glog.log('event_mgr>db_create_event FAILED role_id:%s type:%d' % (role_id, event_type))
        return False, 'db_create_event FAILED'

    # 内存
    event = Event()
    event.id = id
    event.role_id = role_id
    event.type = event_type
    if event.role_id not in data:
        data[event.role_id] = []
    data[event.role_id].append(event)
    event.start()
    print "================after start"

    print "event_mgr data:", data
    return True, ''


def remove_event (role_id, event_type):
    global data
    event = _get_events_by_role_id_and_type(role_id, event_type)
    if event:
        # 数据库
        if not db_delete_event(event.id):
            glog.log('event_mgr>db_delete_event FAILED role_id:%s type:%d' % (role_id, event_type))
            return False, 'db_delete_event FAILED'

        # 内存
        data[event.role_id].remove(event)

    print "event_mgr data:", data
    return True, ''



# 获取玩家当前事件类型
def get_role_current_event_type (role_id):
    events = _get_events_by_role_id(role_id)
    if len(events) > 0:
        return events[0].type
    return -1



# 得到事件的描述
def get_event_desc (event_type):
    if event_type == -1:
        return "发呆中"
    return DATA_HangUp.data[event_type]['desc']




def _dbevent_to_event(dbevent, event):
    event.id = dbevent.id
    event.role_id = dbevent.role_id
    event.type = dbevent.type
    #event.start_time = dbevent.start_time


# ------------------------------------------------------
def db_create_event (id, role_id, type):
    ses = gdb.get_session()
    start_time = datetime.datetime.now()

    try:
        ses.add(DBEvent(id, role_id, type, start_time))
        ses.commit()
        return True
    except Exception, e:
        ses.rollback()
        return False


def db_delete_event (id):
    ses = gdb.get_session()

    dbevent = db_get_event(id)
    if dbevent is None:
        glog.error("event_mgr>db_delete_event FAILED (no this id:%s)", id)
        return False

    ses.delete(dbevent)
    ses.commit()
    return True
    

def db_get_event (id):
    ses = gdb.get_session()
    return ses.query(DBEvent).filter_by(id=id).first()


def db_get_events_by_role_id (role_id):
    ses = gdb.get_session()
    return ses.query(DBEvent).filter_by(role_id=role_id).all()


def db_get_all_events ():
    ses = gdb.get_session()
    return ses.query(DBEvent).all()

